<template>
  <div class="barcode-wrapper">
    <img ref="barcodeRef" class="barcode" />
    <div class="bar-code-text">{{ value }}
      <el-button type="text" @click="copy(value)">复制</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, getCurrentInstance } from 'vue';
import JsBarcode from 'jsbarcode';
import { ElMessage } from 'element-plus'; // 引入ElMessage

// 定义props
const props = defineProps({
  value: {
    type: String,
    default: ''
  }
});

// 引用DOM元素
const barcodeRef = ref(null);

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    JsBarcode(barcodeRef.value, String(props.value), {
      width: 1,
      height: 40,
      displayValue: false,
      fontSize: 15,
      background: "#f5f5f5",
      lineColor: "#000",
      margin: 0
    });
  });
});

// 复制方法
const copy = (content) => {
  // 创建输入框元素
  const input = document.createElement('input');
  input.value = content;
  document.body.appendChild(input);
  input.select();
  document.execCommand('Copy');
  
  // 显示成功提示
  ElMessage({
    message: '复制成功',
    type: 'success'
  });
  
  // 清理DOM
  input.remove();
};
</script>

<style scoped>
.barcode-wrapper {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 5px 10px;
  align-items: center;
  flex-direction: column;
}

.barcode {
  max-width: 375px !important;
}
.bar-code-text {
  margin-top: 5px;
  text-align: center;
}
</style>